<template>
    <div class="container">
        <Breadcrumb :items="['menu.store', 'menu.store.order']" />
        <a-card :title="$t('menu.store.order')">
            <!-- 搜索筛选区域 -->
            <div class="search-form">
                <a-row :gutter="16">
                    <a-col :span="6">
                        <a-input
                            v-model="searchForm.keyword"
                            placeholder="搜索订单号/收货人/电话"
                            allow-clear
                            @press-enter="handleSearch"
                        />
                    </a-col>
                    <a-col :span="4">
                        <a-select
                            v-model="searchForm.status"
                            placeholder="订单状态"
                            allow-clear
                        >
                            <a-option :value="0">待付款</a-option>
                            <a-option :value="1">已付款</a-option>
                            <a-option :value="2">已发货 / 待提货</a-option>
                            <a-option :value="3">已完成</a-option>
                            <a-option :value="4">已取消</a-option>
                            <a-option :value="5">已退款</a-option>
                        </a-select>
                    </a-col>
                    <a-col :span="4">
                        <a-select
                            v-model="searchForm.pay_status"
                            placeholder="支付状态"
                            allow-clear
                        >
                            <a-option :value="0">未支付</a-option>
                            <a-option :value="1">已支付</a-option>
                            <a-option :value="2">已退款</a-option>
                        </a-select>
                    </a-col>
                    <a-col :span="4">
                        <a-select
                            v-model="searchForm.express_type"
                            placeholder="配送方式"
                            allow-clear
                        >
                            <a-option value="pickUpPoint">自提点</a-option>
                            <a-option value="express">快递配送</a-option>
                        </a-select>
                    </a-col>
                    <a-col :span="6">
                        <a-space>
                            <a-button type="primary" @click="handleSearch">
                                <template #icon>
                                    <icon-search />
                                </template>
                                搜索
                            </a-button>
                            <a-button @click="handleReset">重置</a-button>
                        </a-space>
                    </a-col>
                </a-row>
            </div>

            <a-space style="margin-bottom: 16px;">
                <a-card  title="快递配送订单统计">
                    <a-space>
                        <template v-for="item in statusData.statusList" :key="item.status">
                            <a-statistic :extra="item.name" :value="item.num" />
                        </template>
                    </a-space>
                </a-card>
                <a-card title="自提点订单统计">
                    <a-space >
                        <template v-for="item in statusData.status2List" :key="item.status">
                            <a-statistic :extra="item.name" :value="item.num" :value-style="{ color: '#0fbf60' }"/>
                        </template>
                    </a-space>
                </a-card>
            </a-space>


            <!-- 订单列表表格 -->
            <a-table 
                :data="renderData" 
                :loading="loading" 
                :bordered="{ cell: true }" 
                :pagination="pagination"
                @page-change="onPageChange" 
                @page-size-change="onPageSizeChange"
                :scroll="{ x: 1400 }"
            >
                <template #columns>
                    <a-table-column title="ID" data-index="id" width="80" />
                    <a-table-column title="商品信息" width="250">
                        <template #cell="{ record }">
                            <div v-if="record.items && record.items.length > 0" class="goods-info">
                                <div v-for="(item, index) in record.items" :key="item.id" class="goods-item">
                                    <div class="goods-title">{{ index + 1 }}. {{ item.goods_title }}</div>
                                </div>
                            </div>
                        </template> 
                    </a-table-column>
                    <a-table-column title="会员信息" width="200">
                        <template #cell="{ record }">
                            <div class="user-details" v-if="record.user">

                                <div class="phone">{{ record.user.phone }}</div>
                                <div class="vip-status" v-if="record.user.vip_at > 0">
                                    <a-tag color="gold">VIP会员</a-tag>
                                </div>
                            </div>
                        </template>
                    </a-table-column>
                    <a-table-column title="订单金额" width="150">
                        <template #cell="{ record }">
                            <div class="amount-info">
                                <div class="total-amount">总金额: ¥{{ record.total_amount }}</div>
                                <div class="pay-amount">实付: ¥{{ record.pay_amount }}</div>
                                <div class="discount-amount" v-if="record.discount_amount > 0">
                                    优惠: -¥{{ record.discount_amount }}
                                </div>
                            </div>
                        </template>
                    </a-table-column>
                    <a-table-column title="订单状态" width="120">
                        <template #cell="{ record }">
                            <a-tag :color="getStatusColor(record.status)" size="large">
                                {{ record.status_text }}
                            </a-tag>
                        </template>
                    </a-table-column>
                    <a-table-column title="支付状态" width="120">
                        <template #cell="{ record }">
                            <a-tag :color="getPayStatusColor(record.pay_status)" size="large">
                                {{ record.pay_status_text }}
                            </a-tag>
                        </template>
                    </a-table-column>
                    <a-table-column title="配送信息" width="200">
                        <template #cell="{ record }">
                            <div class="delivery-info">
                                <div class="delivery-type">
                                    <a-tag :color="record.express_type === 'pickUpPoint' ? 'blue' : 'green'" size="large">
                                        {{ record.express_type_text }}
                                    </a-tag>
                                </div>
                                <div v-if="record.express_type === 'pickUpPoint' && record.pick_up_point" class="pickup-point">
                                    <div class="point-name">{{ record.pick_up_point.name }}</div>
                                </div>
                                <div v-else-if="record.receiver_name" class="receiver-info">
                                    <div class="receiver-name">{{ record.receiver_name }}</div>
                                    <div class="receiver-phone">{{ record.receiver_phone }}</div>
                                    <div class="receiver-address">
                                        {{ record.delivery_province }} {{ record.delivery_city }} {{ record.delivery_district }}
                                    </div>
                                </div>
                            </div>
                        </template>
                    </a-table-column>

                    <a-table-column title="付款时间" data-index="pay_time" width="180">
                        <template #cell="{ record }">
                            {{ record.pay_status === 1 ? record.pay_time : '-' }}
                        </template>
                    </a-table-column>
                    <a-table-column title="操作" width="180" fixed="right">
                        <template #cell="{ record }">
                            <a-space>
                                <a-button size="small" @click="handleViewDetail(record)">
                                    查看
                                </a-button>
                                <a-dropdown>
                                    <a-button size="small">
                                        操作
                                        &nbsp;<icon-down />
                                    </a-button>
                                    <template #content>
                                        <a-doption @click="handleUpdateStatus(record, 1)" v-if="record.status === 0">
                                            标记已付款
                                        </a-doption>
                                        <a-doption @click="handleUpdateStatus(record, 2)" v-if="record.status === 1">
                                            {{ record.express_type === 'pickUpPoint' ? '标记已提货' : '标记已发货' }}
                                        </a-doption>
                                        <a-doption @click="handleUpdateStatus(record, 3)" v-if="record.status === 2">
                                            标记已完成
                                        </a-doption>
                                        <a-doption @click="handleUpdateStatus(record, 4)" v-if="record.status < 3">
                                            取消订单
                                        </a-doption>
                                    </template>
                                </a-dropdown>
                            </a-space>
                        </template>
                    </a-table-column>
                </template>
            </a-table>
        </a-card>

        <!-- 订单详情弹窗 -->
        <a-modal
            v-model:visible="detailVisible"
            title="订单详情"
            width="800px"
            :footer="false"
        >
            <div v-if="currentOrder" class="order-detail">
                <a-descriptions :column="2" bordered>
                    <a-descriptions-item label="订单号">{{ currentOrder.order_no }}</a-descriptions-item>
                    <a-descriptions-item label="订单状态">
                        <a-tag :color="getStatusColor(currentOrder.status)">
                            {{ currentOrder.status_text }}
                        </a-tag>
                    </a-descriptions-item>
                    <a-descriptions-item label="支付状态">
                        <a-tag :color="getPayStatusColor(currentOrder.pay_status)">
                            {{ currentOrder.pay_status_text }}
                        </a-tag>
                    </a-descriptions-item>
                    <a-descriptions-item label="支付方式">
                        {{ currentOrder.pay_method_text }}
                    </a-descriptions-item>
                    <a-descriptions-item label="订单金额">¥{{ currentOrder.total_amount }}</a-descriptions-item>
                    <a-descriptions-item label="实付金额">¥{{ currentOrder.pay_amount }}</a-descriptions-item>
                    <a-descriptions-item label="优惠金额" v-if="currentOrder.discount_amount > 0">
                        -¥{{ currentOrder.discount_amount }}
                    </a-descriptions-item>
                    <a-descriptions-item label="云豆支付">{{ currentOrder.score }}</a-descriptions-item>
                    <a-descriptions-item label="福利卡云豆">{{ currentOrder.card_score }}</a-descriptions-item>
                    <a-descriptions-item label="创建时间">{{ currentOrder.created_at }}</a-descriptions-item>
                    <a-descriptions-item label="支付时间" v-if="currentOrder.pay_time">
                        {{ currentOrder.pay_time }}
                    </a-descriptions-item>
                    <a-descriptions-item label="订单状态">
                        {{ currentOrder.status_text }}
                    </a-descriptions-item>
                    <a-descriptions-item label="发货状态">
                        {{ currentOrder.delivery_status_text }}
                    </a-descriptions-item>
                    <a-descriptions-item label="配货员工" v-if="currentOrder.express_send_user_id > 0">
                        {{ currentOrder.express_send_user_name }}
                    </a-descriptions-item>
                </a-descriptions>

                <a-divider />

                <div class="goods-list">
                    <h4>商品清单</h4>
                    <a-table :data="currentOrder.items || []" :pagination="false">
                        <template #columns>
                            <a-table-column title="商品图片" width="80">
                                <template #cell="{ record }">
                                    <a-image
                                        :src="record.goods_image"
                                        :width="60"
                                        :height="60"
                                        fit="cover"
                                    />
                                </template>
                            </a-table-column>
                            <a-table-column title="商品信息" data-index="goods_title" />
                            <a-table-column title="规格" data-index="sku_spec_names" />
                            <a-table-column title="单价" data-index="unit_price">
                                <template #cell="{ record }">¥{{ record.unit_price }}</template>
                            </a-table-column>
                            <a-table-column title="数量" data-index="quantity" />
                            <a-table-column title="小计" data-index="final_price">
                                <template #cell="{ record }">¥{{ record.final_price }}</template>
                            </a-table-column>
                        </template>
                    </a-table>
                </div>
            </div>
        </a-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { IconSearch, IconUser, IconDown } from '@arco-design/web-vue/es/icon';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryOrderList, OrderRecord, updateOrderStatus ,queryOrderStatusData} from '@/api/order';

const { loading, setLoading } = useLoading(true);

const basePagination = {
    current: 1,
    pageSize: 10,
    total: 0,
};

const pagination = reactive({
    ...basePagination,
});

// 搜索表单
const searchForm = reactive({
    keyword: '',
    status: undefined,
    pay_status: undefined,
    express_type: undefined,
});

// 生成表单数据
const generateFormData = () => {
    return {
        id: 0,
    };
};

const formData = ref(generateFormData());
const renderData = ref<OrderRecord[]>([]);

// 详情弹窗
const detailVisible = ref(false);
const currentOrder = ref<OrderRecord | null>(null);

// 获取数据
const fetchData = async () => {
    setLoading(true);
    try {
        const { data } = await queryOrderList({
            current: pagination.current,
            pageSize: pagination.pageSize,
            ...searchForm,
        });
        renderData.value = data.list;
        pagination.total = data.total;
    } catch (err) {
        Message.error('获取订单列表失败');
    } finally {
        setLoading(false);
    }
};

// 搜索
const handleSearch = () => {
    pagination.current = 1;
    fetchData();
};

// 重置搜索
const handleReset = () => {
    Object.assign(searchForm, {
        keyword: '',
        status: undefined,
        pay_status: undefined,
        express_type: undefined,
    });
    pagination.current = 1;
    fetchData();
};

// 分页
const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
};

const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
};

// 查看详情
const handleViewDetail = (record: OrderRecord) => {
    currentOrder.value = record;
    detailVisible.value = true;
};

// 更新订单状态
const handleUpdateStatus = async (record: OrderRecord, status: number) => {
    const statusText = getStatusText(status);
    Modal.confirm({
        title: '确认操作',
        content: `确定要将订单状态更新为"${statusText}"吗？`,
        onOk: async () => {
            try {
                await updateOrderStatus(record.id, status);
                Message.success('状态更新成功');
                fetchData();
            } catch (err) {
                Message.error('状态更新失败');
            }
        },
    });
};

// 获取状态文本
const getStatusText = (status: number) => {
    const statusMap = {
        0: '待付款',
        1: '已付款',
        2: '已发货',
        3: '已完成',
        4: '已取消',
        5: '已退款',
    };
    return statusMap[status] || '未知';
};

// 获取状态颜色
const getStatusColor = (status: number) => {
    const colorMap = {
        0: 'orange',
        1: 'blue',
        2: 'purple',
        3: 'green',
        4: 'red',
        5: 'red',
    };
    return colorMap[status] || 'default';
};

// 获取支付状态颜色
const getPayStatusColor = (payStatus: number) => {
    const colorMap = {
        0: 'orange',
        1: 'green',
        2: 'red',
    };
    return colorMap[payStatus] || 'default';
};


// 订单状态数量
const statusData = ref([]);
const fetchStatusData = ()=>{
    queryOrderStatusData().then(res=>{
        statusData.value = res.data;
    })
}

onMounted(() => {
    fetchData();
    fetchStatusData();
});
</script>

<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;
}

.search-form {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
}

.user-details {
    display:flex;
    min-width: 0;
    flex-direction: column;
}

.amount-info {
    .total-amount {
        font-weight: 500;
        margin-bottom: 2px;
    }

    .pay-amount {
        color: #f53f3f;
        font-weight: 500;
        margin-bottom: 2px;
    }

    .discount-amount {
        color: #00b42a;
        font-size: 14px;
    }
}

.delivery-info {
    .delivery-type {
        margin-bottom: 8px;
    }

    .pickup-point, .receiver-info {
        font-size: 14px;
        display:flex;
        color: #666;
    }
}

.goods-info {
    .goods-item {
        padding:0 0 4px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
            border-bottom: none;
        }

        .goods-title {
            font-weight: 500;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .goods-specs {
            color: #666;
            font-size: 14px;
            margin-bottom: 2px;
        }

        .goods-price {
            color: #f53f3f;
            font-size: 14px;
        }
    }

    .more-goods {
        color: #999;
        font-size: 14px;
        text-align: center;
        padding: 4px 0;
    }
}

.order-detail {
    .goods-list {
        margin-top: 16px;

        h4 {
            margin-bottom: 14px;
        }
    }
}


</style>

<script lang="ts">
export default {
    name: 'OrderIndex',
};
</script>